package com.example.lexiangbackend.controller;

import com.example.lexiangbackend.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
@CrossOrigin(origins = "http://localhost:8080")
public class FileUploadController {

    @Autowired
    private AuthService authService;

    // 基础路径配置
    @Value("${file.upload.path:lexiangbackend/src/main/uploads}")
    private String uploadBasePath;
    
    private final String COVERS_DIR = "/covers/";
    private final String SONGS_DIR = "/songs/";
    
    /**
     * 上传封面图片
     */
    @PostMapping("/cover")
    public ResponseEntity<?> uploadCover(@RequestParam("file") MultipartFile file,
                                        @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 验证管理员权限
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足，请先登录管理员账户"));
            }
            
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("请选择要上传的封面图片"));
            }
            
            // 验证文件类型
            if (!isValidImageFile(file)) {
                return ResponseEntity.badRequest().body(createErrorResponse("仅支持JPG、PNG、GIF格式的图片文件"));
            }
            
            // 验证文件大小（限制为5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return ResponseEntity.badRequest().body(createErrorResponse("封面图片大小不能超过5MB"));
            }
            
            String fileName = generateFileName(file.getOriginalFilename());
            String filePath = saveFile(file, COVERS_DIR, fileName);
            String fileUrl = "/api/files/covers/" + fileName;
            
            Map<String, Object> response = createSuccessResponse("封面上传成功");
            response.put("fileName", fileName);
            response.put("filePath", filePath);
            response.put("fileUrl", fileUrl);
            response.put("fileSize", file.getSize());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("封面上传失败: " + e.getMessage()));
        }
    }
    
    /**
     * 上传音乐文件
     */
    @PostMapping("/song")
    public ResponseEntity<?> uploadSong(@RequestParam("file") MultipartFile file,
                                       @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 验证管理员权限
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足，请先登录管理员账户"));
            }
            
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("请选择要上传的音乐文件"));
            }
            
            // 验证文件类型
            if (!isValidAudioFile(file)) {
                return ResponseEntity.badRequest().body(createErrorResponse("仅支持MP3、WAV、FLAC、AAC格式的音频文件"));
            }
            
            // 验证文件大小（限制为50MB）
            if (file.getSize() > 50 * 1024 * 1024) {
                return ResponseEntity.badRequest().body(createErrorResponse("音乐文件大小不能超过50MB"));
            }
            
            String fileName = generateFileName(file.getOriginalFilename());
            String filePath = saveFile(file, SONGS_DIR, fileName);
            String fileUrl = "/api/files/songs/" + fileName;
            
            Map<String, Object> response = createSuccessResponse("音乐文件上传成功");
            response.put("fileName", fileName);
            response.put("filePath", filePath);
            response.put("fileUrl", fileUrl);
            response.put("fileSize", file.getSize());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("音乐文件上传失败: " + e.getMessage()));
        }
    }
    
    /**
     * 批量上传（音乐文件 + 封面）
     */
    @PostMapping("/batch")
    public ResponseEntity<?> uploadBatch(
            @RequestParam(value = "songFile", required = false) MultipartFile songFile,
            @RequestParam(value = "coverFile", required = false) MultipartFile coverFile,
            @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 验证管理员权限
            if (!isAdmin(token)) {
                return ResponseEntity.badRequest().body(createErrorResponse("权限不足，请先登录管理员账户"));
            }
            Map<String, Object> result = new HashMap<>();
            
            // 上传音乐文件
            if (songFile != null && !songFile.isEmpty()) {
                if (!isValidAudioFile(songFile)) {
                    return ResponseEntity.badRequest().body(createErrorResponse("音频文件格式不支持"));
                }
                if (songFile.getSize() > 50 * 1024 * 1024) {
                    return ResponseEntity.badRequest().body(createErrorResponse("音乐文件大小不能超过50MB"));
                }
                
                String songFileName = generateFileName(songFile.getOriginalFilename());
                String songFilePath = saveFile(songFile, SONGS_DIR, songFileName);
                String songFileUrl = "/api/files/songs/" + songFileName;
                
                Map<String, Object> songInfo = new HashMap<>();
                songInfo.put("fileName", songFileName);
                songInfo.put("filePath", songFilePath);
                songInfo.put("fileUrl", songFileUrl);
                songInfo.put("fileSize", songFile.getSize());
                result.put("song", songInfo);
            }
            
            // 上传封面文件
            if (coverFile != null && !coverFile.isEmpty()) {
                if (!isValidImageFile(coverFile)) {
                    return ResponseEntity.badRequest().body(createErrorResponse("封面图片格式不支持"));
                }
                if (coverFile.getSize() > 5 * 1024 * 1024) {
                    return ResponseEntity.badRequest().body(createErrorResponse("封面图片大小不能超过5MB"));
                }
                
                String coverFileName = generateFileName(coverFile.getOriginalFilename());
                String coverFilePath = saveFile(coverFile, COVERS_DIR, coverFileName);
                String coverFileUrl = "/api/files/covers/" + coverFileName;
                
                Map<String, Object> coverInfo = new HashMap<>();
                coverInfo.put("fileName", coverFileName);
                coverInfo.put("filePath", coverFilePath);
                coverInfo.put("fileUrl", coverFileUrl);
                coverInfo.put("fileSize", coverFile.getSize());
                result.put("cover", coverInfo);
            }
            
            Map<String, Object> response = createSuccessResponse("文件上传成功");
            response.put("files", result);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse("批量上传失败: " + e.getMessage()));
        }
    }
    
    // ================================ 私有方法 ================================
    
    /**
     * 验证图片文件类型
     */
    private boolean isValidImageFile(MultipartFile file) {
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        
        if (contentType != null) {
            return contentType.startsWith("image/") && 
                   (contentType.equals("image/jpeg") || 
                    contentType.equals("image/png") || 
                    contentType.equals("image/gif") ||
                    contentType.equals("image/webp"));
        }
        
        if (fileName != null) {
            String extension = fileName.toLowerCase();
            return extension.endsWith(".jpg") || 
                   extension.endsWith(".jpeg") || 
                   extension.endsWith(".png") || 
                   extension.endsWith(".gif") ||
                   extension.endsWith(".webp");
        }
        
        return false;
    }
    
    /**
     * 验证音频文件类型
     */
    private boolean isValidAudioFile(MultipartFile file) {
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        
        if (contentType != null) {
            return contentType.startsWith("audio/") || 
                   contentType.equals("application/octet-stream");
        }
        
        if (fileName != null) {
            String extension = fileName.toLowerCase();
            return extension.endsWith(".mp3") || 
                   extension.endsWith(".wav") || 
                   extension.endsWith(".flac") || 
                   extension.endsWith(".aac") ||
                   extension.endsWith(".ogg") ||
                   extension.endsWith(".m4a");
        }
        
        return false;
    }
    
    /**
     * 生成唯一文件名
     */
    private String generateFileName(String originalFilename) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        String uuid = UUID.randomUUID().toString().substring(0, 8);
        String extension = "";
        
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        
        return timestamp + "_" + uuid + extension;
    }
    
    /**
     * 保存文件到指定目录
     */
    private String saveFile(MultipartFile file, String directory, String fileName) throws IOException {
        // 创建完整的目录路径
        Path dirPath = Paths.get(uploadBasePath + directory);
        Files.createDirectories(dirPath);
        
        // 保存文件
        Path filePath = dirPath.resolve(fileName);
        Files.copy(file.getInputStream(), filePath);
        
        return filePath.toString();
    }
    
    /**
     * 创建成功响应
     */
    private Map<String, Object> createSuccessResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", message);
        return response;
    }
    
    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return response;
    }
    
    /**
     * 验证管理员权限
     */
    private boolean isAdmin(String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return false;
            }
            String jwt = token.substring(7);
            String role = authService.extractRoleFromToken(jwt);
            return "ADMIN".equals(role);
        } catch (Exception e) {
            return false;
        }
    }
} 